﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Security.Cryptography;
using System.IO;

namespace CommModule.Security
{
    public class SimmEncryption
    {
        private static readonly byte[] _initializationVector = { (byte)0x19, (byte)0xa5, (byte)0xd6, (byte)0x9d, (byte)0xc9, (byte)0xa8, (byte)0xe9, (byte)0xea, (byte)0xe6, (byte)0x74, (byte)0x1e, (byte)0xa5, (byte)0x39, (byte)0x35, (byte)0x73, (byte)0xb7 };

        public static String Cipher(String toCipher, byte[] key)
        {
            AesManaged aes = new AesManaged();
            aes.BlockSize = 128;
            aes.Mode = CipherMode.CBC;
            aes.Padding = PaddingMode.PKCS7;
            aes.Key = key;
            aes.IV = _initializationVector;

            byte[] toCipherBytes = Encoding.UTF8.GetBytes(toCipher);

            MemoryStream ms = new MemoryStream();

            CryptoStream cs = new CryptoStream(ms, aes.CreateEncryptor(), CryptoStreamMode.Write);

            cs.Write(toCipherBytes, 0, toCipherBytes.Length);
            cs.FlushFinalBlock();

            byte[] cipheredBytes = ms.ToArray();

            return Convert.ToBase64String(cipheredBytes);
        }

        public static String Decipher(String toDecipher, byte[] key)
        {
            AesManaged aes = new AesManaged();
            aes.BlockSize = 128;
            aes.Mode = CipherMode.CBC;
            aes.Padding = PaddingMode.PKCS7;
            aes.Key = key;
            aes.IV = _initializationVector;

            byte[] toDecipherBytes = Convert.FromBase64String(toDecipher);

            MemoryStream ms = new MemoryStream();

            CryptoStream cs = new CryptoStream(ms, aes.CreateDecryptor(), CryptoStreamMode.Write);

            cs.Write(toDecipherBytes, 0, toDecipherBytes.Length);
            cs.FlushFinalBlock();

            byte[] decipheredString = ms.ToArray();

            return Encoding.UTF8.GetString(decipheredString);
        }
    }
}
